package com.miracle.erp.servlet.user;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.apache.bcel.internal.generic.NEW;

import com.miracle.erp.service.IUserService;
import com.miracle.erp.util.AjaxObj;
import com.miracle.erp.util.ERPException;
import com.miracle.erp.util.ObjectFactory;
import com.miracle.erp.model.User;

@WebServlet("/user/add")
public class UserAddServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			// 获取页面输入的数据 然后封装交给service
			
			// 获取传递的数据
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			String nickname = req.getParameter("nickname");
			// integer.parseInt()是把()里的内容转换成整数
			int age = Integer.parseInt(req.getParameter("age"));
			int sex = Integer.parseInt(req.getParameter("sex"));
			
			// 封装给User
			// 利用工厂创建对象
			User user = ObjectFactory.getUser();
			// 保存值
			user.setUsername(username);
			user.setPassword(password);
			user.setNickname(nickname);
			user.setSex(sex);
			user.setAge(age);
			// 测试 user是否获得值
			System.out.println(user);
	
			// 怎么把它们送进数据库
			// 逻辑操作在这里调用 创建实例化对象 然后调用需要的方法
			IUserService  userService = ObjectFactory.getUserService();
			// 调用添加的方法 这里就需要去创建接口    创建实现类的方法
			try {
				userService.add(user);
				resp.getWriter().println(new AjaxObj(1,"添加成功").toJSON());
			} catch (ERPException e) {
				resp.getWriter().println(new AjaxObj (0,e.getMessage()).toJSON());
			}
			
	}	
}
